// pages/shoppingCart/shoppingCart.js
var appdata = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    newbk:'',
    idCart:[],
    appCart:[],
    totalCount:0,//总本数
    totalScore:0, //积分总和
    isSelectAll:false,
    pageIndex:1,
    pageSum:0
  },

  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取购物车中id数组
    this.getOrderMsg()
  },
  // 获取订单列表
  getOrderMsg(){
    wx.request({
      url: 'http://124.222.95.170:21311/shoppingCart/page',
      method:'GET',
      header: {
        'Cookie': wx.getStorageSync('sessionid')
      },
      data:{
        "page":this.data.pageIndex,
        "pageSize":6
      },
      success:(res)=>{
        let sum = res.data.data.total
        let carts = this.data.appCart.length == 0 ? res.data.data.records : this.data.appCart.concat(res.data.data.records) ;
        let total = this.data.totalCount;
        //添加isSelect属性
        for(let i = 0; i < carts.length; i++){
          if(!carts[i]['isSet']){
            carts[i]['isSelect']= false;
            carts[i]['isSet'] = true
            total++;
          }
        }
        this.setData({
          appCart:carts,
          totalCount:total,
          pageSum:sum
        })
        this.getTotalPrice()
      }
    })
  },
  // 计算总积分
  getTotalPrice(){
    let carts = this.data.appCart;                  // 获取购物车列表
    let total = 0;
    let count = 0;
    let status = this.data.isSelectAll;
    for (let i = 0; i < carts.length; i++) {         // 循环列表得到每个数据
      if (carts[i].isSelect) {                   // 判断选中才会计算价格
        total += carts[i].goods.integral;   // 所有价格加起来
        count++;
      }
    }
    if(count == carts.length) status = true;
    else status = false
    this.setData({                                // 最后赋值到data中渲染到页面
      appCart: carts,
      totalScore: total,
      totalCount:count,
      isSelectAll : status
    });
    appdata.globalData.cartList = this.data.appCart
  },
    // 单选
  bindCheckbox(e){
    let that = this
    let idx = e.currentTarget.dataset.index
    let carts = that.data.appCart;
    const isSelect1 = carts[idx].isSelect;
    
    if(carts[idx].goods.status == 1){
      carts[idx].isSelect = !isSelect1;
      that.setData({
        appCart: carts,
        selectAll: false
      })
    }else{
      wx.showToast({
        title: '该书已下架，无法购买',
        icon:'none'
      })
    }
    
    that.getTotalPrice()
  },
  // 全选
  bindSelectAll(e){
    let carts = this.data.appCart;
    let total = this.data.totalScore;
    let count = carts.length;
    let allSelectStatus = !this.data.isSelectAll;
    let nowTotal = 0;
    for(let i = 0; i < count; i++){
      if(carts[i].goods.status == 1){
        carts[i].isSelect = allSelectStatus
        if(carts[i].isSelect){
          nowTotal += carts[i].goods.integral
        }
      }
      
    }
    this.setData({
      appCart : carts,
      totalScore : nowTotal,
      isSelectAll : allSelectStatus
    })
  },
  // 删除
  bindDelete(e){
    wx.showModal({
      cancelColor: '#000000',
      title:'提示',
      content:'您确定要删除这本书吗',
      cancelText:'再看看',
      success:(res)=>{
        if(res.confirm){
          let idx = e.currentTarget.dataset.index
          let carts = this.data.appCart;
          let theScore = carts[idx].goods.integral
          let total = this.data.totalScore
          let count = this.data.totalCount
          let status = this.data.isSelectAll
          let id = []
          id.push(carts[idx].goods.id)
          if(carts[idx].isSelect) total -= theScore
          count--;
          if(count <= 0) status = false;
          wx.request({
            url: 'http://124.222.95.170:21311/shoppingCart',
            method:'DELETE',
            header: {
              'Cookie': wx.getStorageSync('sessionid')
            },
            data: id,
            success:(res)=>{
              console.log('成功',res)
              if(res.data.data == "删除成功"){
                carts.splice(idx,1)
                wx.showToast({
                  title: '删除成功',
                  icon:'none'
                })
              }
              this.setData({                                // 最后赋值到data中渲染到页面
                appCart: carts,
                totalScore: total,
                totalCount: count,
                isSelectAll:status
              });
            },
          })
          
          
        } 
      }
    })
  },
    // 结算
  bindjiesuan(e){
    let carts = this.data.appCart;
    let finalCart = [];
    var j = 0, i = 0;
    for(; j < carts.length; j++){
      if(carts[j].isSelect == true){
        finalCart[i] = carts[j];
        i++
      } 
    
    }
    wx.setStorageSync('bookCarts', finalCart)
    wx.navigateTo({
      url: '../settle/settle?totalScore='+this.data.totalScore
    })

  }, 
  // 跳转至详情页
  goTodetails(e){
    // console.log(e.currentTarget.dataset.msg)
    let msg = e.currentTarget.dataset.msg
    wx.navigateTo({
      url: '/pages/xiangqing/xiangqing?shuji='+ JSON.stringify(msg)
    })
  },
  // 上拉加载更多
  onReachBottom() {
    console.log('reach bottom!')
    if(this.data.pageIndex * 5 >= this.data.pageSum){
      wx.showToast({
        title: '已经到底啦',
        icon:'none'
      })
      return
    }
    this.setData({
      pageIndex:this.data.pageIndex + 1
    })
    this.onLoad()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})